//index.js
//获取应用实例
const app = getApp()
var url = require('../../utils/url.js');
//计数器
var interval = null;
var dataCode;
//值越大旋转时间越长  即旋转速度
var intime = 25;
var token;
var formid;
var userinfo;
var openId;
var shareUSER=0;
var session;
var base64 = require('../../utils/base64.js');
var USERID;
var jiangType;
var Jname;
var share_num;
Page({
  data: {
    color: [0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
    //9张奖品图片
    images: [],
    btnconfirm: '/images/dianjichoujiang.png',
    clickLuck: 'clickLuck',
    luckPosition: "0",
    info:"",
    log:"",
    luckyIdx:"",
    jiang:true,
    kuai2: url.IMGURL + "kuai2.png",
    kuai: url.IMGURL+"kuai.png",
    chance:0,
    formid:"",
    meidenglu:true,
    rulesArray:"",
    share1:true
  },
  ying:function(){
     this.setData({
       share1:true
     })
  },
  getActivity(userId){
    var that=this;
    wx.request({
      url: url.URl + 'activity',
      data: {user_id:userId},
      method: 'get',
      header: {
        'Authorization': token
      },
      success: function (res) {
        console.log(res)
        var msg = res.data.msg;
        if (res.data.code == 200) {
          share_num = res.data.data.share_num;
          var rules = res.data.data.info.info.rules;
          var rulesArray = rules.split("|");
          console.log(rulesArray)
          var data = res.data.data.info.awards;
          for(var i=0;i<data.length;i++){
            data[i].idx=i
          }
          var chance=res.data.data.chance;
          if (chance==null){
            chance=0;
          }else{
            chance = res.data.data.chance
          }
          that.setData({
            images: data,
            info: res.data.data.info.info,
            log: res.data.data.info.log,
            chance: chance,
            rulesArray: rulesArray
          })

          console.log(data)
          wx.hideLoading()
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onLoad: function (options) {
    console.log("用户id" + options.userId)
    if (options.userId){
      wx.setStorage({
        key: 'rec_id',
        data: options.userId,
      })
      shareUSER = options.userId
    }else{
      shareUSER=0;
    }
  },

  input: function (e) {
    var data = e.detail.value;
    this.setData({
      luckPosition: data
    })
  },


  //点击抽奖按钮
  clickLuck: function (e) {
    // token=wx.getStorageInfoSync("token")

    var that = this;
    var chance = that.data.chance;
    token = wx.getStorageSync("token")
    if (token){
     
      var goods = this.data.images;

      // console.log(token)
      if  (chance != 0) {
        var e = this;
        e.setData({
          luckPosition: ""
        })
        wx.request({
          url: url.URl + 'activity/lottery',
          data: {},
          method: 'post',
          header: {
            'Authorization': token
          },
          success: function (res) {
            console.log(res)
            var msg = res.data.msg;
            if (res.data.code == 200) {
              jiangType=res.data.data.type;
              chance = chance - 1
              let luckyIdx = goods.filter(function (v) {
                console.log(v)
                if (v.id == res.data.data.rid) {
                  return true;
                } else {
                  return false;
                }
              }).map(function (v) {
                return v;
              });
              console.log(luckyIdx)
              Jname = luckyIdx[0].name;
              e.setData({
                luckPosition: luckyIdx[0].idx,
                luckyIdx: luckyIdx,
                chance: chance
              })
              dataCode = 200;
            } else if (res.data.code == 201) {
              dataCode = 201;
              chance = chance - 1;
              let luckyIdx = goods.filter(function (v) {
                // console.log(goods)
                if (v.type == 1) {
                  return true;
                } else {
                  return false;
                }
              }).map(function (v) {
                return v.idx;
              });
              console.log(luckyIdx)
              e.setData({
                luckPosition: luckyIdx[0],
                chance: chance
              })
            } else if (res.data.code == 401) {
              wx.showModal({
                title: '',
                content: '您的登录已过期请，重新登录',
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#D13B17',
                success: function (res) {
                  if (res.confirm) {

                  }
                },
                fail: function (res) { },
                complete: function (res) { },
              })
            }
          }
        })
        //判断中奖位置格式
        if (e.data.luckPosition == null || isNaN(e.data.luckPosition) || e.data.luckPosition > 7) {
          wx.showModal({
            title: '提示',
            content: '请填写正确数值',
            showCancel: false,
          })
          return;
        }



        //设置按钮不可点击
        e.setData({
          btnconfirm: '/images/dianjichoujiangd.png',
          clickLuck: '',
        })
        //清空计时器
        clearInterval(interval);
        var index = 0;
        // console.log(e.data.color[0]);
        //循环设置每一项的透明度
        interval = setInterval(function () {
          if (index > 7) {
            index = 0;
            e.data.color[7] = 0.5
          } else if (index != 0) {
            e.data.color[index - 1] = 0.5
          }
          e.data.color[index] = 1
          e.setData({
            color: e.data.color,
          })
          index++;
        }, intime);

        //模拟网络请求时间  设为两秒
        var stoptime = 2000;
        setTimeout(function () {
          e.stop(e.data.luckPosition);
        }, stoptime)
      } else {
        that.setData({
          share1:true
        })
        console.log(share_num)
        that.getLast()
      }
    }else{
      console.log(e.detail.formId);
      that.toDenglu(e)
    }
    


  },

  colse(){
     this.setData({
       jiang:true
     })
  },
  //也可以写成点击按钮停止抽奖
  // clickStop:function(){
  //   var stoptime = 2000;
  //   setTimeout(function () {
  //     e.stop(1);
  //   }, stoptime)
  // },

  stop: function (which) {
    var e = this;
    //清空计数器
    clearInterval(interval);
    //初始化当前位置
    var current = -1;
    var color = e.data.color;
    for (var i = 0; i < color.length; i++) {
      if (color[i] == 1) {
        current = i;
      }
    }
    //下标从1开始
    var index = current + 1;

    e.stopLuck(which, index, intime, 10);
  },


  /**
   * which:中奖位置
   * index:当前位置
   * time：时间标记
   * splittime：每次增加的时间 值越大减速越快
   */
  stopLuck: function (which, index, time, splittime) {
    var e = this;
    //值越大出现中奖结果后减速时间越长
    var color = e.data.color;
    setTimeout(function () {
      //重置前一个位置
      if (index > 7) {
        index = 0;
        color[7] = 0.5
      } else if (index != 0) {
        color[index - 1] = 0.5
      }
      //当前位置为选中状态
      color[index] = 1
      e.setData({
        color: color,
      })
      //如果旋转时间过短或者当前位置不等于中奖位置则递归执行
      //直到旋转至中奖位置
      if (time < 200 || index != which) {
        //越来越慢
        splittime++;
        time += splittime;
        //当前位置+1
        index++;
        e.stopLuck(which, index, time, splittime);
      } else {
        //1秒后显示弹窗
        setTimeout(function () {
          if (dataCode == 200) {
            //中奖
            e.setData({
              btnconfirm: '/images/dianjichoujiang.png',
              clickLuck: 'clickLuck',
            })
            if (jiangType==4){
              wx.showModal({
                title: '恭喜获得' + Jname,
                content: '获得的积分可参与积分幸运星！',
                showCancel: false,
                success:function(res){
                  if(res.confirm){
                   
                  }
                }
              })
            } 
            // else if (jiangType == 2){
            //   wx.showModal({
            //     title: '恭喜获得' + Jname,
            //     content: '赶紧去买商品吧！',
            //     showCancel: false,
            //     success: function (res) {
            //       if (res.confirm) {
            //         wx.switchTab({
            //           url: 'pages/index/index',
            //         })
            //       }
            //     }
            //   })
            // }
            else{
              e.setData({
                jiang: false
              })
            }
          } else {
            wx.showModal({
              title: '提示',
              content: '谢谢参与',
              showCancel: false,
              confirmText: '我知道了',
              confirmColor: '#B76514',
              success: function(res) {
                if (res.confirm) {
                  //设置按钮可以点击
                  e.setData({
                    btnconfirm: '/images/dianjichoujiang.png',
                    clickLuck: 'clickLuck',
                  })
                  // e.loadAnimation();
                }
              },
            })
          }
        }, 1000);
      }
    }, time);
    // console.log(time);
  },
  copyBtn: function (e) {
    var that = this;
    wx.setClipboardData({
      data: that.data.info.weixin,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    });
  },
  //进入页面时缓慢切换
  loadAnimation: function () {
    var e = this;
    var index = 0;
    // if (interval == null){
    interval = setInterval(function () {
      if (index > 7) {
        index = 0;
        e.data.color[7] = 0.5
      } else if (index != 0) {
        e.data.color[index - 1] = 0.5
      }
      e.data.color[index] = 1
      e.setData({
        color: e.data.color,
      })
      index++;
    }, 1000);
    // }  
  },
  onShow:function(){
    var that=this;
    wx.getStorage({
      key: 'token',
      success: function (res) {
        token = res.data
        that.setData({
          meidenglu: true
        })
      },
      fail:function(){
        that.setData({
          meidenglu:false
        })
      }
    })
    wx.getStorage({
      key: 'userinfo',
      success: function (res) {
        userinfo = res.data;
        USERID = userinfo.id;
        that.getActivity(USERID);
      },fail:function(){
      }
    })
    
  },
  getLast(){
    var that=this;
    wx.request({
      url: url.URl3 + 'user/getshare',
      data: {},
      method: 'get',
      header: {
        'Authorization': token
      },
      success: function (res) {
          if(res.data.code==201){
            wx.showModal({
              title: '提示',
              content: '今天抽奖次数已经用完，获得的积分可参与积分幸运星',
              showCancel: true,
              confirmText: '立即前往',
              concelText: '我知道了',
              confirmColor: '#DD2626',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/luckyStar/luckyStar',
                  })
                }
              },
              fail: function (res) { },
              complete: function (res) { },
            })
          }else if(res.data.code==200){
            wx.showModal({
              title: '提示',
              content: '转发分享获得抽奖次数',
              showCancel: false,
              confirmText: '我知道了',
              confirmColor: '#DD2626',
              success: function (res) { },
              fail: function (res) { },
              complete: function (res) { },
            })
          }
      }
    })
  },
toDenglu:function(e){
    var that = this;
    var formid = e.detail.formId
    this.setData({
      formid: formid
    })
    formid = e.detail.formId;
    wx.showToast({
      title: '登录中',
      icon: 'loading',
    })
    wx.login({
      success: function (response) {
        var code = response.code
        console.log(response)
        if (response.code) {
          wx.getUserInfo({
            success: function (resp) {
              var nickName = resp.userInfo.nickName;
              var avatarUrl = resp.userInfo.avatarUrl;
              wx.request({
                url: url.URl + 'login/mini',
                data: { code: code },
                method: 'POST',
                success: function (res) {

                  console.log(res.data)

                  userinfo = resp.userInfo;
                  var jsonopenId;
                  var basepenId
                  openId = res.data.data.openid;

                  let data = {};
                  var openID = "openid";
                  let from = "from"
                  var type = "type";
                  var mini_formid = "mini_formid";
                  var nickName1 = "nickName";
                  var avatarUrl1 = "avatar";
                  var shareUser = "share_user";
                  data[openID] = openId;
                  data[nickName1] = nickName;
                  data[type] = "share";
                  data[from] = "mini";
                  data[avatarUrl1] = avatarUrl;
                  data[mini_formid] = formid;
                  data[shareUser] = shareUSER;
                  console.log(data)
                  jsonopenId = JSON.stringify(data)
                  // console.log(jsonopenId)
                  basepenId = base64.Base64.encode(jsonopenId)
                  console.log(basepenId)
                  var session = res.data.data.session_key;
                  var enBasepenId = encodeURIComponent(basepenId)
                  console.log(enBasepenId)
                  wx.request({
                    url: url.URl + 'login',
                    data: { ihy: enBasepenId },
                    method: 'POST',
                    success: function (res) {
                      var msg = res.data.data
                      console.log(res)
                      if (res.data.code == 200) {
                        // console.log(res)
                        that.setData({
                          meidenglu: true,
                        })
                        var userinfo = res.data.data.userInfo;
                        USERID = userinfo.id
                        token = res.data.data.token;
                        that.setData({
                          userinfo: userinfo
                        })
                        wx.setStorage({
                          key: 'userinfo',
                          data: userinfo,
                        })
                        wx.setStorage({
                          key: 'token',
                          data: token,
                        })
                        wx.hideToast()
                        wx.showToast({
                          title: '登录成功',
                          icon: 'success',
                          duration: 2000,
                          success: function () {
                            that.getActivity(USERID);
                            if (userinfo.phone == null) {
                              wx.showModal({
                                title: '绑定手机号',
                                content: '为了参加活动后客服联系您',
                                showCancel: true,
                                cancelText: '暂不绑定',
                                confirmText: '去绑定',
                                confirmColor: '#DD2626',
                                success: function(res) {
                                  if (res.confirm) {
                                    wx.navigateTo({
                                      url: '/pages/my_setPhone/my_setPhone',
                                    })
                                  }
                                },
                                fail: function(res) {},
                                complete: function(res) {},
                              })
                            }
                          }
                        })
                      } else {
                        wx.showToast({
                          title: msg,
                          icon: 'success',
                          duration: 2000,
                          success: function () {
                          }
                        })
                      }
                    }
                  })
                }
              })

            }, fail: function () {
              console.log("用户拒绝授权")
              wx.hideLoading()
            }
          })
        } else {
          console.log('获取用户登录态失败！' + response.errMsg)
        }
      }
    });
  },
  getChance(){
    var that=this;
    wx.request({
      url: url.URl3 + 'user/share/rand',
      data: {},
      method: 'get',
      header: {
        'Authorization': token
      },
      success: function (res) {
        console.log(res.data)
        var msg = res.data.msg;
        wx.hideLoading();
        that.getActivity(USERID)
        if (res.data.code == 200) {
          
          setTimeout(() => {
            wx.showToast({
              title: msg,
              icon: 'none',
            })
          }, 3500);
        } else if(res.data.code==201){
          
          setTimeout(() => {
            wx.showToast({
              title: msg,
              icon: 'none',
            })
          }, 3500);
        } else if (res.data.code == 203){
          setTimeout(() => {
            wx.showModal({
              title: '提示',
              content: msg,
              showCancel: true,
              cancelText: '我知道了',
              confirmText: '立即前往',
              confirmColor: '#DD2626',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/luckyStar/luckyStar',
                  })
                }
              },
              fail: function (res) { },
              complete: function (res) { },
            })
          }, 3500);
          
        }
      }
    });
  },
  onShareAppMessage: function (res) {
   this.setData({
     share1:true
   })
    setTimeout(() => {
      // 模拟请求数据，并渲染
      this.getChance()
    }, 1000); 
    if (res.from === 'button') {
    }
    return {
      title: '幸运大转盘',
      path: '/pages/turntable/turntable?userId=' + USERID,
    }
  },
})